package com.hpin.fansea.utils;


import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.jpush.android.api.JPushInterface;

public class JpushReceiver extends BroadcastReceiver {
	private static final String TAG = "JPushReceiver";
	
	public static final String MESSAGE_RECEIVED_ACTION = "ccom.hpin.fansea.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
//	public static String uid = "";
	 private NotificationManager nm;
	@Override
	public void onReceive(Context context, Intent intent) {
		
		LogUtil.e("jpush", "收到了一条消息=================>");
		
		if (context == null || intent == null)
			return;
	
		Bundle bundle = intent.getExtras();
		if (bundle == null)
			return;
		
		 if (null == nm) {
	            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
	        }
	        
	        LogUtil.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
	        
	        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
	            LogUtil.d(TAG, "JPush用户注册成功");
	             
	        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
	            LogUtil.e(TAG, "接受到推送下来的自定义消息");
	            receivingNotification(context,bundle);
	            
	        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
	            LogUtil.d(TAG, "接受到推送下来的通知");
	            
	//	            receivingNotification(context,bundle);
	 
	        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
	            LogUtil.d(TAG, "用户点击打开了通知");
	        
	//	           openNotification(context,bundle);
	           
	        } else {
	            LogUtil.d(TAG, "Unhandled intent - ACTION ==>" + intent.getAction());
	        }
		
	}
			
	 private void receivingNotification(Context context, Bundle bundle){
		 	
	        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
	        LogUtil.e(TAG, " title : " + title);
	        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
	        LogUtil.e(TAG, "message : " + message);
	        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
	        LogUtil.e(TAG, "extras : " + extras);
	        
        	try {
				
        	   	JSONObject extraJson = JSON.parseObject(extras);
            	
            	if (extraJson!=null) {
    				
            		String first_type = extraJson.getString("first_type");
            		String second_type = extraJson.getString("second_type");
            		
            		LogUtil.e(TAG, "first_type : " + first_type + ",second_type : " + second_type);


					openNotifate(context, message, title);

//            		//用户在当前的app
//                	boolean isExist = context.getPackageName().equals(getRunningPackageName(context));
//
//            		if (Constant.SYSTEM_MESSAGE.equals(first_type)) {
//        				//系统消息
//                		if (!isExist) {
//							//用户不在app 通知
//                			//TODO
////                			openNotifate(context, message, title);
//						} else {
//							sendBroad(context, message, first_type, second_type);
//						}
//
//        			}else if (Constant.HOUSEKEEPER_MESSAGE.equals(first_type)) {
//        				//我的消息
//
//        				if (Constant.HOUSEKEEPER_TENANT_YES.equals(second_type) || Constant.HOUSEKEEPER_TENANT_NO.equals(second_type)
//        						|| Constant.HOUSEKEEPER_SYSTEM_JOBORDER.equals(second_type)) {
//							//通过 || 驳回  || 系统派单
//        					//通知栏通知
//
//        					sendBroad(context, message, first_type, second_type);
//
//						}else {
//
//							if (!isExist) {
////								//用户不在app 通知
//								//TODO
////	        					openNotifate(context, message, title);
//							}else {
//								sendBroad(context, message, first_type, second_type);
//							}
//
//						}
//
//        			}else if (Constant.HOUSEKEEPER_GROPORDER.equals(first_type)) {
//        				//抢单
//                    	sendBroad(context, message, first_type, second_type);
//
//        			}
    			}
			} catch (Exception e) {
			}
	    }

	private void sendBroad(Context context, String message, String first_type,
			String second_type) {
		Intent intent=new Intent();
		intent.setAction("com.hpin.wiwj.ACTION_HOUSEKEE_GROPORDER");
		intent.putExtra("first_type", first_type);
		intent.putExtra("second_type", second_type);
		intent.putExtra("message", message);
		context.sendBroadcast(intent);
	}

	@Deprecated
	private void openNotifate(Context context, String message, String title) {
		
//        //通知栏打开通知
//    	NotificationManager nManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
//		Notification notify = new Notification();
//		// 设置通知在状态栏显示的图标
//		notify.icon = R.drawable.ic_launcher;
//		// 通知时发出的声音
//		notify.defaults = Notification.DEFAULT_SOUND;
//
//		//点击通知后自动删除通知
//		notify.flags = Notification.FLAG_AUTO_CANCEL;
//		//打开我的消息页面
//		Intent intent = new Intent(context, HomeActivity.class);
//		//context.getPackageName().equals(getRunningPackageName(context)) ? null :
//		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//		notify.setLatestEventInfo(context, title, message, contentIntent);
//
//		nManager.notify(0, notify);
		
	}
	
//   private void openNotification(Context context, Bundle bundle){
//        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//        String myValue = "";
//        try {
//            JSONObject extrasJson = new jsonJSONObject(extras);
//            myValue = extrasJson.optString("myKey");
//            
//            LogUtil.e("jpush", "===================openNotification==========");
//            //用户未打开我们的应用
//		if (!context.getPackageName().equals(getRunningPackageName(context))) {
//			PackageManager packageManager = context.getPackageManager();
//			Intent intent = new Intent();
//			try {
//				intent = packageManager.getLaunchIntentForPackage("com.app.mingluxing");
//			} catch (Exception e) {
//				LogUtil.e(TAG, e.toString());
//			}
//			context.startActivity(intent);
//		}
//            
//        } catch (Exception e) {
//            LogUtil.e("jpush", "Unexpected: extras is not a valid json");
//            return;
//        }
//    }
	
	// 打印所有的 intent extra 数据
	private String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} 
			else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}
		
	/**
	 * 获得当前运行的app的包名
	 * @return
	 */
	private String getRunningPackageName(Context ctx){
		ActivityManager activityManager=(ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
		 String packageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
		return packageName;                 
	}
//
//	private void openMessageActivity(Context context, Bundle bundle) {
//		
//		
//		
//		// 打开自定义的Activity 	TODO
////		if (MainActivity.instance != null) {
////			// 打开消息中心
////			MainActivity.instance.switchCurrentFragment(2);
////		}
//	}
//
//	// send msg to MainActivity
//	private void processCustomMessage(Context context, Bundle bundle) {
//		MessageInfo msg = new MessageInfo();
//		try {
//			String msg_id = bundle.getString(JPushInterface.EXTRA_MSG_ID);
//			String alert = bundle.getString(JPushInterface.EXTRA_ALERT);
//			String title = bundle.getString(JPushInterface.EXTRA_TITLE);// 自定义标题
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			// String push_time = bundle.getString(JPushInterface.EXTRA_);
//
//			msg.setMsg_id(msg_id);
//			msg.setAlert(alert);
//			msg.setTitle(title);
//			// msg.setPush_time(push_time);
//
//			Intent msgIntent = new Intent(MESSAGE_RECEIVED_ACTION);
//
//			 if (extras != null && extras.length() > 0) {
//			
//			 JSONObject extraJson = JSON.parseObject(extras);
//			 if (null != extraJson) {
//			 // msgIntent.putExtra(KEY_EXTRAS, extras);
//			
//			 String msg_body_type = extraJson.getString("msg_body_type");
//			 String msg_sub_type = extraJson.getString("msg_sub_type");
//			 String push_time = extraJson.getString("push_time");
//			 String content = extraJson.getString("url");
//			
////			 msg.setMsg_body_type(msg_body_type);
////			 msg.setMsg_sub_type(msg_sub_type);
////			 msg.setPush_time(push_time);
////			 msg.setContent(content);
//			 }
//			 }
//
//			// 存数据库
//			// MessageInfoDatabase.save(context, msg, uid );
//			msgIntent.putExtra("message", msg);
//
//			LogUtil.e("TAG", "极光推送的消息========>" + msg.toString());
//
//			context.sendBroadcast(msgIntent);
//		} catch (Exception e) {
//			Log.e("JPushReceiver", e.toString());
//		}
//	}
}
